<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/9/1
 * Time: 10:43
 */
// 充值  升级会员
class StartbakAction extends BaseAction{
	protected $share_info;
    //魔术方法
    public function __construct()
    {
        parent::__construct();
		$memberinfo=$this->getMemberInfo();
		if($memberinfo['member_vip_type'] == 0){
			$code=$_GET['share'];
			$code=$code ? $code :$memberinfo['recommend_code'];
            $share_vip_type=M('member')->where('member_card="'.$code.'"')->getField('member_vip_type');
			if($share_vip_type==0){
				$code=$memberinfo['recommend_code'];
			}
		}else{
			$code=$memberinfo['recommend_code'];
		}
		$share_info=M('member')->where('member_card="'.$code.'"')->find();
		$this->share_info = $share_info;
		$this->assign('share_info',$share_info);
    }

    //订单列表
    public function index()
    { 
		$member_info=$this->getMemberInfo();
        $levelinfo=M('member_level')->select();
        $this->assign('levelinfo',$levelinfo);
        $this->assign('member_info',$member_info);
        $this->display();
    }

    //vip 特权
    public function vip_tq()
    {
        $this->display();
    }

    
    //推荐人信息
    public function basic(){
        $levelId=$_GET['levelId'];
        $test=M('member_level')->find();
        $memberinfo=$this->getMemberInfo();
        $this->member=$memberinfo;
        $data=$this->getMemberCode($memberinfo['recommend_code']);
        $recommend_name=M('member')->where(array('member_card'=>$data['recommend_code']))->getField('member_name');
        $data['recommend_name']=$recommend_name;
        $flageship_info=getflageship($memberinfo['recommend_code']);
        $data['flageship']=$flageship_info['member_name'];
        $data['levelId']=$levelId;
        $this->data=$data;
        $this->webtitle="FG峰购";
        $this->display();
    }


    //直接下单买
    public function start_set_order()
    {
        $levelId=$_POST['levelId'];
        $return_data['status'] = 0;
        $uid = $_SESSION['member']['uid'];

        if (empty($_SESSION['member']['mobile'])) {
            //未绑定  手机
            $return_data['status'] = 2;
            $return_data['error'] = '请完善资料';
            echo json_encode($return_data);
            die;
        }
        $level_info=M('member_level')->where(array('levelId'=>$levelId))->find();
        $member_info=$this->getMemberInfo();
        $member_level=$member_info['member_vip_type'];
        $last_level_info=M('member_level')->where('levelId='.$member_info['member_vip_type'])->find();
        $time = time();
        $pay_sn = makePaySn($uid); //生成订单号
        //升级的差价
        if($member_level==0){
            $pay_price=$level_info['price'];
        }else{
            $pay_price=$last_level_info['upgrade_price'];
        }
        //订单信息
            //升级订单信息
        $level_order_data['id']=$pay_sn;
        $level_order_data['levelId']=$levelId;//要升级的用户等级
        $level_order_data['member_id'] = $uid;//升级用户
        $level_order_data['upgrade_time'] = date("Y-m-d H:i:s",$time);//升级时间
        $level_order_data['last_level']=$member_level;//当前用户等级
            //商品订单信息
        $order_data['order_sn'] = $pay_sn;
        $order_data['user_id'] = $uid;
        $order_data['is_gift'] = 0;//活动类型0 无 1 限时抢购
        $order_data['is_upgrade'] = 1;//升级产品
        $order_data['goods_amount'] = $level_info['price'];//商品总金额
        $order_data['order_amount'] = $pay_price;//应付款金额
        $order_data['order_cost'] = 0;//成本
        $order_data['pay_note'] = I('pay_note');//备注
        $order_data['add_time'] = $time;
		if($this->share_info){
			$share_info = $this->share_info;
			$order_data['share_uid'] = isset($share_info['id']) ? $share_info['id'] : 0;
		}elseif (isset($member_info['recommend_code']) && $member_info['recommend_code']){
            $share_info = M('member')->where('member_card="'.$member_info['recommend_code'].'"')->find();
            $order_data['share_uid'] = isset($share_info['id']) && $share_info['id'] ? $share_info['id'] : 0;
        }
		
        //订单付款信息
        $order_pay_data['buyer_id'] = $uid;
        $order_pay_data['pay_sn'] = $pay_sn;

        $level_order_data['pay_price']=$pay_price;//要支付的价格
        $level_order_data['pay_status']=0;
        //获取要用的数据库对象
        $level_order_model=M('member_level_order');
        $order_model = M('g_order_info');
        $order_goods_model = M('g_order_goods');
        $order_pay_model = M('g_order_pay');

        $level_order_model->startTrans();//开启事务
        $order_model->startTrans();//开起事务
        $order_goods_model->startTrans();//开起事务
        $order_pay_model->startTrans();//开起事务

        $add_order = $order_model->add($order_data);
        $add_level_order = $level_order_model->add($level_order_data);

        if ($add_order === false||$add_level_order === false) {
            $return_data['error'] = "订单生成失败，请稍后再试.";
            $level_order_model->rollback();//回滚事务
            $order_model->rollback();//回滚事务
            $order_goods_model->rollback();//回滚事务
            $order_pay_model->rollback();//回滚事务
            echo json_encode($return_data);
            die;
        }
        //g_order_goods的信息
        $order_good_data['order_id'] = $add_order;
        $order_good_data['goods_id'] = 0;
        $order_good_data['goods_name'] = '升级成'.$level_info['levelName'];//商品名
        $order_good_data['goods_sn'] = 0;//商品的唯一货号
        $order_good_data['goods_price'] = $level_info['price'];//商品价格
        $order_good_data['market_price'] = $level_info['price'];//商品价格
        $order_good_data['purchase_price'] = 0;//进价
        $order_good_data['goods_number'] = 1;//商品数量
        $order_good_data['goods_image'] = '';//
        $order_good_data['goods_attr_id'] =  $pay_price;//商品实际成交价
        $order_good_data['goods_attr'] = '';//商家id
        $order_good_data['share_card'] = $member_info['recommend_code'];//分享者 card
        $order_good_data['share_id'] ;//分享者 id

        $order_good_data['share_money'] ;//分享返利金额
        $order_good_data['is_refund'] = 0;//是否可退货 1是 0否
        $order_good_data['goods_shipping'] ;//包邮方式 默认SF顺风包邮
        $order_good_data['shipping_code'];//包邮方式code
        $order_good_data['offline'] = 0;//货到付款
        $order_good_data['is_exchange'] = 0;////是否可退货 1是 0否
        $order_good_data['is_gift'] =0;//活动类型0 无 1 限时抢购
        $order_good_data['promote_start_date'] ;
        $order_good_data['promote_end_date'] ;
        $order_good_data['is_upgrade'] = 1;//升级产品
        $add_order_goods[] = $order_goods_model->add($order_good_data);


        $add_order_pay = $order_pay_model->add($order_pay_data);
        if ($add_order !== false && $add_order_pay !== false&&$add_level_order !== false) {
            $return_data['status'] = 1;
            //记录订单日志
            $level_order_model->commit();
            $order_model->commit();//提交事务
            $order_goods_model->commit();//提交事务
            $order_pay_model->commit();//提交事务
            $data = array();
            $data['order_id'] = $add_order;
            $data['order_amount'] = 1;
            M('g_pay_log')->add($data);
            //记录订单日志
            $data = array();
            $data['order_id'] = $add_order;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = '用户下单成功';
            $data['log_orderstate'] = '10';
            D('Mallorder')->addOrderLog($data);
            $return_data['need_pay'] = 1;///需要支付 1  不需要支付0
            $return_data['pay_sn'] = $pay_sn;
        } else {
            $order_model->rollback();//回滚事务
            $order_pay_model->rollback();//回滚事务
            $order_goods_model->rollback();//回滚事务
            $level_order_model->rollback();//回滚事务
            $return_data['error'] = "订单生成失败，请稍后再试.";
        }
        echo json_encode($return_data);
        die;
    }
    //订单详情页


    //付款页面
    public function  start_pay(){
        $pay_sn=$_REQUEST['pay_sn'];
        $level_order_info=M('member_level_order')->where(array('id'=>$pay_sn))->find();
        //$order_id=M('g_order_info')->where('order_sn='.$level_order_info['id'])->getField('order_id');
        $level_info=M('member_level')->where('levelId='.$level_order_info['levelId'])->find();
		$share_info=$this->share_info;
        $data=$level_order_info;
        $data['levelName']=$level_info['levelName'];
        $data['member_name']=$this->member_name;//用户名
        //$data['order_id']=$order_id;
        $memberinfo_de = $this->getMemberDetail();
		$memberinfo_de['recommend_name'] = $share_info['member_name'];
        $memberinfo_de['balance'] += $memberinfo_de['balance_give'];
        $this->MemberDetail = $memberinfo_de;
        $balance = $memberinfo_de['balance'];
        $balance = sprintf("%.2f", substr(sprintf("%.3f", $balance), 0, -2));
        $this->balance = $balance;
        // var_dump($data);
        // exit;

        // 支付状态；0，未付款；1，付款中 ；2，已付款

        $pay_status = array('0' => '未付款', '1' => '已支付，对账中', '2' => '已付款');
        $this->pay_status = $pay_status;

        $title = "订单信息";
        //$this->assign("data", $data);
        $this->data=$data;
        $this->display();
    }

    public function start_pay_go(){

        $return_data['status'] = 0;
        $order_id = $_REQUEST['order_id'];
        $uid = $this->uid;
        $mem_password = $_REQUEST['mem_password'];
        $pay_type = $_REQUEST['pay_type'];
        $use_balance = $_REQUEST['use_balance'];
        //购买开关
        $buy_switch = M('sys_param')->where(array('param_code' => 'buy_switch'))->getField('param_value');
        if (empty($buy_switch)) {
            $return_data['error'] = '管理员已关闭交易';
            echo json_encode($return_data);
            die;
        }
        $model_order = D('Mallorder');
        if ($pay_type == "pay_online") {//在线支付
            if ($use_balance) {//使用余额支付
                $this->balance_pay();
                die;
            } else {
                $condition = array();
                $condition['id'] = $order_id;
                $level_order_list=M('member_level_order')->where($condition)->find();
                $order_list = $model_order->getOrderList($condition, '', 'order_id,order_sn,order_amount,shipping_fee,surplus,surplus_give,discount_start_time,discount_end_time,discount');
                if (empty($level_order_list)||empty($order_list)) {
                    $return_data['error'] = "该订单不存在";
                    echo json_encode($return_data);
                    die;
                }
                ////未使用余额支付
                $_GET['return'] = 1;
                $_GET['pay_sn'] = $level_order_list['id'];
                //$get_pay_url = $this->get_pay_url();
                $return_data['need_pay'] = 1;///需要支付 1  不需要支付0
                $return_data['status'] = 1;
                /* if ($get_pay_url['status'] == 1) {
                     $return_data['status'] = 1;
                     $return_data['pay_url'] = $get_pay_url['pay_url'];
                 } else {
                     $return_data['error'] = $get_pay_url['error'];
                     $return_data['status'] = 0;
                 }*/
                echo json_encode($return_data);
                die;
            }
        }
    }
    ///余额支付
    public function balance_pay()
    {
        $return_data['status'] = 0;
        $order_sn = $_REQUEST['order_id'];//由于两个表字段名不一样
        $order_id=M('g_order_info')->where("order_sn=$order_sn")->getField();
        $uid = $this->uid;
        $mem_password = $_REQUEST['mem_password'];
        $pay_type = $_REQUEST['pay_type'];

        if (empty($mem_password)) {
            $return_data['error'] = "密码不能为空";
            echo json_encode($return_data);
            die;
        }
        $member = $this->getMemberInfo();
        if ($member['password'] != md5($mem_password)) {
            $return_data['error'] = "密码错误";
            echo json_encode($return_data);
            die;
        }
        $memberinfo_de = $this->getMemberDetail();
        if (empty($memberinfo_de)) {
            $return_data['error'] = "用户不存在";
            echo json_encode($return_data);
            die;
        }
        $balance = $memberinfo_de['balance'] + $memberinfo_de['balance_give'];
        $balance = sprintf("%.2f", substr(sprintf("%.3f", $balance), 0, -2));
        if ($balance <= 0) {
            $return_data['error'] = "余额不足";
            echo json_encode($return_data);
            die;
        }
        $model_order = D('Mallorder');
        //重新计算在线支付且处于待支付状态的订单总额
        $condition = array();
        $condition['order_id'] = $order_id;
        $condition['pay_status'] = '0';// 支付状态；0，未付款；1，付款中 ；2，已付款
        $order_list = $model_order->getOrderList($condition, '', 'order_id,order_sn,user_id,order_amount,shipping_fee,is_upgrade,surplus,surplus_give,discount_start_time,discount_end_time,discount,offline,offline_money');
        if (empty($order_list)) {
            $return_data['error'] = "该订单不存在";
            echo json_encode($return_data);
            die;
        }
        //计算本次需要在线支付的订单总金额
        $time = time();
        $pay_amount = 0;
        $offline_money = 0;
        $fee_offline_money = 0;//加运费的货到付款总额
        foreach ($order_list as $order_info) {
            $pay_amount += PriceFormat(floatval($order_info['shipping_fee']));//运费
            ///减去余额支付部分 减去折扣部分
            ///折扣是否过期
            if ($order_info['discount_start_time'] <= $time && $order_info['discount_end_time'] >= $time) {
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['surplus']) - floatval($order_info['discount']));
            } else {
                $pay_amount += PriceFormat(floatval($order_info['order_amount']) - floatval($order_info['surplus']));
            }
            if ($order_info['offline']) {
                $pay_amount -= $order_info['offline_money'];//
            }

        }

        //如果为空，说明已经都支付过了或已经取消或者是价格为0的商品订单，全部返回
        if (empty($pay_amount)) {
            $return_data['error'] = "订单金额为0，不需要支付";
            echo json_encode($return_data);
            die;
        }

        $consume_record_model = M('member_consume_record');
        $member_detail_model = M('member_detail');
        $model_order = M('g_order_info');
        $need_pay = 1;//还需要支付现金
        $m_s_data = array();
        $surplus_give = 0;///支付的赠送余额
        if ($pay_amount > $balance) {//订单金额大于余额  扣除所有余额

            $m_s_data['balance_give'] = 0;///扣除所有赠送余额
            //扣除余额 加上 赠送余额
            $m_s_data['balance'] = $memberinfo_de['balance'] - $balance + $memberinfo_de['balance_give'];//余额
            $surplus_give = $memberinfo_de['balance_give'];
            $money = $balance;
        } else {//订单金额小于等于 余额
            if ($pay_amount > $memberinfo_de['balance_give']) {
                //支付金额 大于 赠送余额 扣除全部赠送余额
                $m_s_data['balance_give'] = 0;
                $m_s_data['balance'] = $memberinfo_de['balance'] - $pay_amount + $memberinfo_de['balance_give'];
                $surplus_give = $memberinfo_de['balance_give'];
            } else {
                //支付金额 小于 等于赠送余额 扣除订单金额的赠送余额
                $m_s_data['balance_give'] = $memberinfo_de['balance_give'] - $pay_amount;
                $surplus_give = $pay_amount;
            }
            $need_pay = 0;//不需要支付现金
            $money = $pay_amount;
        }
        $time = time();
        $log = array();
        $log['status'] = 0;//支出
        $log['add_time'] = $time;
        $log['member_id'] = $uid;
        $log['money'] = $money;
        $log['type'] = 1;
        $log['des'] = '用户使用余额支付￥' . $money;
        $save_order = array();
        $save_order['surplus'] = $order_list[0]['surplus'] + $money;
        $save_order['surplus_give'] = $order_list[0]['surplus_give'] + $surplus_give;//支付的赠送余额
        if (empty($need_pay)) {
            $save_order['pay_status'] = '2';
            $save_order['pay_time'] = $time;
        }
        $member_detail_model->startTrans();//开起事务
        $consume_record_model->startTrans();//开起事务
        $model_order->startTrans();//开起事务
        $m_res = $member_detail_model->where(array('member_id' => $uid))->save($m_s_data);
        $c_res = $consume_record_model->add($log);
        $order_res = $model_order->where(array('order_id' => $order_id))->save($save_order);

        //in_array如果设置该参数为 true，则检查搜索的数据与数组的值的类型是否相同。
        if ($m_res !== false && $c_res !== false && $order_res !== false) {
            $return_data['status'] = 1;
            $return_data['need_pay'] = $need_pay;
            $log_msg = '用户使用余额支付￥' . $money;
            if ($need_pay) {//需要继续支付
                $_GET['return'] = 1;
                $_GET['pay_sn'] = $order_list[0]['order_sn'];
               /* $get_pay_url = $this->get_pay_url();
                if ($get_pay_url['status'] == 1) {
                    $return_data['pay_url'] = $get_pay_url['pay_url'];
                } else {
                    $return_data['error'] = $get_pay_url['error'];
                    $return_data['status'] = 0;
                }*/
            } else {//余额  支付完成
                //支付完成 发送短信通知
                $this->order_sendSMS($order_list[0]['order_sn'], $save_order['surplus'], '余额支付');
                //购买成功  查询是否是会员 不是会员则升级为会员
                if ($order_list[0]['is_upgrade']) {//升级订单
                    $member = M('member')->where(array('id' => $order_list[0]['user_id']))->field('id,member_vip_type')->find();
                    if ($member && $member['member_vip_type']<2) {
                        //$reee = M('member')->where(array('id' => $order_list[0]['user_id']))->save(array('member_vip_type' => 1,'vip_time'=>time()));
                        $log_msg .= '升级会员成功';
                        $this->upgrade_level($order_list[0]['order_sn']);
                    }
                }

            }

            $model_order->commit();//提交事务
            $consume_record_model->commit();//提交事务
            $member_detail_model->commit();//提交事务
            //记录订单日志
            /* if(empty($need_pay)){//订单支付日志
               $data = array();
               $data['order_id'] = $order_id;
               $data['order_amount'] =$money;
                M('g_pay_log')->add($data);
              }*/
            //记录订单日志
            $data = array();
            $data['order_id'] = $order_id;
            $data['log_role'] = 'buyer';
            $data['log_msg'] = $log_msg;
            if (empty($need_pay)) {
                $data['log_orderstate'] = '20';
            } else {
                $data['log_orderstate'] = '10';
            }
            $insert = D('Mallorder')->addOrderLog($data);
        } else {
            $model_order->rollback();//回滚事务
            $consume_record_model->rollback();//回滚事务
            $member_detail_model->rollback();//回滚事务
            $return_data['error'] = "支付失败请稍候再试.";
        }
        echo json_encode($return_data);
        die;
    }

    //购买升级后选择地址
    public function gift_address(){
        $order_sn=$_GET['order_sn'];
/*        $this->upgrade_level($order_sn);*/

        if ($this->uid) {
            $this->address = M('g_user_address')->where(array('user_id' => $this->uid))->order('is_default desc')->select();
        }
		$this->order_sn = $order_sn;
		$this->city_group = get_city_group();
        $this->display();
    }
    //将地址添加到订单中
    public function add_address(){
		$order_sn=$_REQUEST['order_sn'];
        $address_id = $_REQUEST['select_address_id'];
        $uid = $_SESSION['member']['uid'];
        $return_data['id']=$order_sn;
        if (empty($_SESSION['member']['mobile'])) {
            //未绑定  手机
            $return_data['status'] = 2;
            $return_data['error'] = '请完善资料';
            echo json_encode($return_data);
            die;
        }
        if (empty($address_id)) {
            $return_data['error'] = '请选择收货地址';
            echo json_encode($return_data);
            die;
        }
        $address = M('g_user_address')->where(array('address_id' => $address_id, 'user_id' => $uid))->find();
        if (empty($address)) {
            $return_data['error'] = '收货地址不存在';
            echo json_encode($return_data);
            die;
        }
        $order_data['consignee'] = $address['consignee'];
        $order_data['province'] = $address['province'];
        $order_data['city'] = $address['city'];//
        $order_data['district'] = $address['area'];//
        $order_data['address'] = $address['address_name'] . $address['address'];//用户消费时的折扣
        $order_data['zipcode'] = $address['zipcode'];//用
        $order_data['tel'] = $address['tel'];//
        $order_data['mobile'] = $address['mobile'];//
        $order_data['email'] = $address['email'];//
        $order_data['best_time'] = $address['best_time'];//收货人的最佳送货时间
        $order_data['sign_building'] = $address['sign_building'];//收货人的地址的标志性建筑
        //$should_pay = $list['need_pay'];  //应付款金额
        $order_model = M('g_order_info');
        $order_model->startTrans();//开起事务
        $add_order = $order_model->where('order_sn="'.$order_sn.'"')->save($order_data);

        if ($add_order === false) {
            $return_data['error'] = "地址添加失败，请稍后再试.";
            $order_model->rollback();//回滚事务
            echo json_encode($return_data);
            die;
        }

        $return_data['status']=1;

        echo json_encode($return_data);
        die;
    }
    //升级订单支付后回调升级信息
    public function upgrade_level($order_sn){
        //g_order_info
        //member_level_order
        //member
        $where['order_sn']=$order_sn;
        $order_info=M('g_order_info')->where($where)->find();
        if($order_info['is_upgrade']){
            $where1['id'] = $order_sn;
            $where1['pay_status'] = 0;
            $level_order_info=M('member_level_order')->where($where1)->find();
            if (!empty($level_order_info)){
				//更新升级订单
                M('member_level_order')->where($where1)->setField('pay_status','1');
				//更新用户信息：升级等级，升级订单状态，升级时间
                $where2['id']=$order_info['user_id'];
				$member_data['member_vip_type']=$level_order_info['levelId'];
				$member_data['member_vip_order']=$level_order_info['levelId'];
				$member_data['vip_time']=time();
				
				//如果有是有人分享的链接来开店，更新推荐人
				$share_info = '';
				$share_detail = '';
				if(isset($order_info['share_uid']) && $order_info['share_uid']){
					$share_info = M('member')->where('id='.$order_info['share_uid'])->find();
					$share_detail = M('member_detail')->where('member_id='.$order_info['share_uid'])->find();
				}
				if($share_info && $share_detail && $level_order_info['last_level'] == 0){
					$member_data['recommend_code'] = $share_info['member_card'];
					$member_data['indirect_recommend_code'] = $share_info['recommend_code'];
					$member_data['indirect2_recommend_code'] = $share_info['indirect_recommend_code'];
					$member_data_detail['relevel'] = $share_detail['relevel'] + 1;
					$member_data_detail['repath'] = $share_detail['repath'].','.$order_info['user_id'];
					M('member_detail')->where('member_id='.$share_info['id'])->setInc('t_m_fans_add');
				}
				if(isset($member_data_detail) && $member_data_detail){
					M('member_detail')->where(array('member_id'=>$order_info['user_id']))->save($member_data_detail);
				}
				M('member')->where($where2)->save($member_data);
				//利润分配
                $ret_exchange = $this->set_member_exchange($order_info);
				return $ret_exchange;
            }else{
                return  "该订单不存在";
            }
        }
    }
	// 升级成旗舰店
    private function setflageship($recommend_code){
        $recommend_info=M('member')->where('member_card="'.$recommend_code.'"')->find();
        $r1_level_info=M('member_level')->where('levelId='.$recommend_info['member_vip_type'])->find();
        $shars=get_fans_count($recommend_info['member_card']);
        $shar_r1=$shars['shar_r1'];
        $shar_r2=$shars['shar_r2'];
        if (($shar_r1+$shar_r2) >= $r1_level_info['upgrade_parm']&& $shar_r1>= $r1_level_info['upgrade_parm2']){
            M('member')->where('member_card="'.$recommend_code.'"')->setField('member_vip_type','3');
        }
    }

public function bak(){
                 //利润分配
               // $ret_exchange = $this->set_member_exchange(525);
                //var_dump( $ret_exchange);	
}	
    /*
	*
	* 利润分配
	* $data_info array：订单信息，必须包括order_id , int：order_id;
	* 返回 status 0错误（msg）为错误信息 1成功
	* kkxx 2016-10-08 
	*/
    private function set_member_exchange($data_info = array()){
		$ret = array();
		$ret['status'] = 0;
		
		if(is_array($data_info)){
			$order_id = $data_info['order_id'];
		}else{
			$order_id = $data_info;
		}
		if(!$order_id){
			$ret['msg'] = '参数错误！';
            return $ret;
		}
		$g_order_info = M('g_order_info');
		// $order_info = $g_order_info->where(array('order_id'=>409))->find();
		$order_info = $g_order_info->where(array('order_id'=>$order_id))->find();
        if (empty($order_info)){
			$ret['msg'] = '没有找到订单';
            return $ret;
        }
		
		if($order_info['pay_status'] != 2){
			$ret['msg'] = '订单没有付款';
            return $ret;
		}
		
		if($order_info['is_upgrade'] != 1){
			$order_status = $this->get_order_status($order_info);
			if ($order_status['code'] != 'delivered') {//已发货
				$ret['msg'] = '订单状态错误';
				return $ret;
			}
		}
		
		$pre = C('DB_PREFIX');//表前缀
		
        //用户自己返利  用户积分增加  返利日志 积分增加日志
		$field = 'mem.id, mem.member_card, mem.mobile, mem.recommend_code, mem.indirect_recommend_code, mem.indirect2_recommend_code, mem.member_status, mem.member_vip_type, mem.member_vip_order, md.provinceid, md.cityid, md.areaid, md.relevel, md.repath';
        $member_info = M()->table($pre . 'member mem')
		->join($pre . 'member_detail md on mem.id=md.member_id')
		->where(array('mem.id' => $order_info['user_id']))
		->field($field)->find();
		
		//shop_rebate_status  123 级返利状态 1 返利  0不返
        $shop_rebate_status = 0;//返利类型 1分享返利 0正常返利(123级返利) 2升级返利
        $member_tuijian_data = array();//返利记录
		
        $order_save_data = array();//订单返利 数据
        $order_save_data['profit_type'] = 0;//返利类型 1分享返利 0正常返利(123级返利)
        $order_save_data['order_profit'] = $order_info['order_amount'];//订单利润= 应付款金额-订单返利
        $order_save_data['order_rebate'] = 0;//订单返利金额
		
		//订单利润
		$is_income = TRUE;
		$money = 0; $c_money = 0; $syb_money = 0;
		if($order_info['is_upgrade'] == 1){
			$level_order = M('member_level_order')->where(array('id'=>$order_info['order_sn']))->find();
			if($level_order['last_level'] > 0){
				$is_income = FALSE;
			}
			$shop_rebate_status = 2;
			$money = $order_info['goods_amount'];
			$syb_money = $order_info['goods_amount'];
		}else{
			$order_goods_info=M('g_order_goods')->where('order_id='.$order_info['order_id'])->select();
			foreach ($order_goods_info as $k=>$v){
				$goods_id=$v['goods_id'];
				$goods_number=$v['goods_number'];
				$goods_price=$v['goods_price'];
				$purchase_price=M('g_goods')->where("goods_id=$goods_id")->getField('purchase_price');
				$money += (($goods_price-$purchase_price)*$goods_number);
			}
			
			$c_money = $money;
		}
		
		if($money <= 0){
			$ret['msg'] = '利润金额错误（'.$money.'）';
			return $ret;
		}

		//如果是升级_设置奖池
		//if(isset($syb_money)){
		//	D('Jackpot')->set_jackpot($syb_money);
		//}

		$money_integral = 10;
		//分配比例
		if($order_info['is_upgrade']==1){
			$rem1_money_ratio = 0.28;
			$rem1_integral_ratio = 0.05;
			$rem2_money_ratio = 0.04;
			$rem2_integral_ratio = 0.02;
			$rem3_money_ratio = 0.03;
			$rem3_integral_ratio = 0.01;
		}else{
			$rem1_money_ratio = 0.3;
			$rem1_integral_ratio = 0.1;
			$rem2_money_ratio = 0.08;
			$rem2_integral_ratio = 0.02;
			$rem3_money_ratio = 0.03;
			$rem3_integral_ratio = 0.02;
		}
		$total_ratio = $rem1_money_ratio + $rem1_integral_ratio + $rem2_money_ratio + $rem3_money_ratio + $rem3_integral_ratio;
		
		//推荐人查找
		$repath = explode(',', $member_info['repath']);
		$member_list_array = M('member')->where(array('id' => array('in', $member_info['repath'])))->select();
		$member_list = array();
		foreach($member_list_array as $item){
			$member_list[$item['id']] = $item;
		}
		
		$i = 0;
		$num = 0;
		$member1_info = $member2_info = $member3_info = '';
		$recommend_member_info = array();
		while($i < $member_info['relevel']){
			$uid = array_pop($repath);
			if($uid != $member_info['id']){
				$num ++;
				$recommend_member_info[$num] = $member_list[$uid];
			}
			$i++;
		}
		
		$member1_info = isset($recommend_member_info[1]) ? $recommend_member_info[1] : '';
		$member2_info = isset($recommend_member_info[2]) ? $recommend_member_info[2] : '';
		$member3_info = isset($recommend_member_info[3]) ? $recommend_member_info[3] : '';
		
		$left_money = $money;
		
		//直接推荐人
		if($is_income && $member1_info && $member1_info['mobile'] && $member1_info['member_vip_type']){
			$member1_money = mb_number($money * $rem1_money_ratio);
			$member1_integral_money = mb_number($money * $rem1_integral_ratio);
			$member1_integral = $member1_integral_money * $money_integral;
			
			if($member1_money > 0 || $member1_integral > 0){
				$order_save_data['order_rebate'] += ($member1_money + $member1_integral);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type']=1;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '直接推荐人('.$member_info['member_card'].')消费收益：￥' . $member1_money;
				
				//金额日志
				$this->set_member_balance($member1_info['id'], 1, $member1_money, $log);
				//积分日志
				$log['des'] = '直接推荐人('.$member_info['member_card'].')消费积分：' . $member1_integral;
				$this->set_member_points($member1_info['id'], 1, ($member1_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member1_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 2;
				$tuijian_data['money'] = $member1_money;
				$tuijian_data['integral'] = $member1_integral;
				$tuijian_data['des'] = '直接推荐人('.$member_info['member_card'].')消费收益：￥' . $member1_money . '，消费积分：' . $member1_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		//间接推荐人
		if($is_income && $member2_info && $member2_info['mobile'] && $member2_info['member_vip_type'] > 1){
			$member2_money = mb_number($money * $rem2_money_ratio);
			$member2_integral_money = mb_number($money * $rem2_integral_ratio);
			$member2_integral = $member2_integral_money * $money_integral;
			
			if($member2_money > 0 || $member2_integral > 0){
				$order_save_data['order_rebate'] += ($member2_money + $member2_integral);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type'] = 2;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $member2_money;
				
				//金额日志
				$this->set_member_balance($member2_info['id'], 1, $member2_money, $log);
				//积分日志
				$log['des'] = '间接推荐人('.$member_info['member_card'].')消费积分：' . $member2_integral;
				$this->set_member_points($member2_info['id'], 1, ($member2_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member2_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 3;
				$tuijian_data['money'] = $member2_money;
				$tuijian_data['integral'] = $member2_integral;
				$tuijian_data['des'] = '间接推荐人('.$member_info['member_card'].')消费收益：￥' . $member2_money . '，消费积分：' . $member2_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		//间接二级推荐人
		if($is_income && $member3_info && $member3_info['mobile'] && $member3_info['member_vip_type'] > 1){
			$member3_money = mb_number($money * $rem3_money_ratio);
			$member3_integral_money = mb_number($money * $rem3_integral_ratio);
			$member3_integral = $member3_integral_money * $money_integral;
			
			if($member3_money > 0 || $member3_integral > 0){
				$order_save_data['order_rebate'] += ($member3_money + $member3_integral);
				
				$log = array();
				$log['type'] = 5;//消费类型 1订单消费 2充值 3提现   4退款 5 收益 6认证消费
				$log['type5_type'] = 3;//收益类型  1直接推荐人 2间接推荐人 3 间接二级推荐人 4代理区域会员
				$log['order_id'] = $order_info['order_id'];
				$log['des'] = '间接二级推荐人('.$member_info['member_card'].')消费收益：￥' . $member3_money;
				
				//金额日志
				$this->set_member_balance($member3_info['id'], 1, $member3_money, $log);
				//积分日志
				$log['des'] = '间接二级推荐人('.$member_info['member_card'].')消费积分：' . $member3_integral;
				$this->set_member_points($member3_info['id'], 1, ($member3_integral), $log);
				
				//收益记录
				$tuijian_data = array();
				$tuijian_data['member_id'] = $member3_info['id'];
				$tuijian_data['order_id'] = $order_info['order_id'];
				$tuijian_data['type'] = 5;
				$tuijian_data['money'] = $member3_money;
				$tuijian_data['integral'] = $member3_integral;
				$tuijian_data['des'] = '间接二级推荐人('.$member_info['member_card'].')消费收益：￥' . $member3_money . '，消费积分：' . $member3_integral;
				$member_tuijian_data[] = $tuijian_data;
			}
		}
		
		$order_save_data['profit_type'] = $shop_rebate_status;
		$order_save_data['order_profit_all'] = $total_ratio * $money;
		//订单利润 order_profit
		//订单返利金额 order_rebate
		//订单返利总金额 返利池 order_profit_all
		$order_save_data['order_profit'] = $order_save_data['order_profit'] - $order_save_data['order_rebate'];
		M('g_order_info')->where(array('order_id' => $order_info['order_id']))->save($order_save_data);
		
		//累计业绩
		$index_num = strrpos($member_info['repath'], ',');
		$yeji_user_ids = substr($member_info['repath'], 0, $index_num);
		if($syb_money > 0){ //累计创业业绩
			M('member_detail')->where(array('member_id'=>array('in', $yeji_user_ids)))->setInc('syb_yeji', $syb_money);
		}
		if($c_money > 0){ //累计消费业绩
			M('member_detail')->where(array('member_id'=>array('in', $yeji_user_ids)))->setInc('c_yeji', $c_money);
		}
		
		if(!empty($member_tuijian_data)) { //写入收益记录
			$rebate_record_model = M('rebate_record');
			$time = time();
			foreach ($member_tuijian_data as $key => $value) {
				$value['add_time'] = $time;
				$value['status'] = 1;//状态 1用户收益 2 商家返利
				$rebate_record_model->add($value);
			}
		}

		$ret['status'] = 1;
		return $ret;
	}

}
